package wx;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import zy.util.HttpUtil;
import zy.util.WeixinUtil;

public class QrCode {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			GetUrl();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public static void GetUrl() throws ClientProtocolException,IOException {

        HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" +  WeixinUtil.my_app_id + "&secret=" +  WeixinUtil.my_app_secret );
        HttpClient httpClient = HttpClients.createDefault();

        HttpResponse res = httpClient.execute(httpGet);
        HttpEntity entity = res.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        JSONObject jsons = JSONObject.parseObject(result);
        String expires_in = jsons.getString("expires_in"); 

        //缓存
        if(Integer.parseInt(expires_in)==7200){
            String access_token = jsons.getString("access_token");

//            Jedis cache = new Jedis("127.0.0.1", 6379);
//            System.out.println("access_token:"+access_token);
//            Pipeline pipeline = cache.pipelined();
//            pipeline.set("access_token", access_token);
//            pipeline.expire("access_token", 7200);
//            pipeline.sync();
            
            try {
				GetPostUrl(access_token,"20");
			} catch (Exception e) {
				e.printStackTrace();
			} 

        }else{
            System.out.println("出错获取token失败！");
        }
    }
		
	//获取二维码 信息图片
    public static String GetPostUrl(String access_token,String id) throws Exception {
        //「菊花式」小程序码
        String url ="https://api.weixin.qq.com/wxa/getwxacode?access_token=";
        //狗皮膏是二维码
        //String url ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=";
         
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("path", "pages/index/index?scene="+id);//你二维码中跳向的地址
        map.put("width", "430");//图片大小
        JSONObject json = JSONObject.parseObject(JSON.toJSONString(map));
        System.out.println(json);
        String  res= httpPostWithJSON(url+ access_token, json.toString(),id);
        System.out.println(res);

        return null;
    }

    //返回图片保存 ，根据 id

    public static String httpPostWithJSON(String url, String json,String id)throws Exception {

        String result = null;

//        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpClient httpClient = HttpUtil.createSSLClientDefault();//createSSLClientDefault();
//        HttpUtil.createSSLClientDefault();

        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        StringEntity se = new StringEntity(json);
        se.setContentType("application/json");
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "UTF-8"));
        httpPost.setEntity(se);

        HttpResponse response = httpClient.execute(httpPost);

        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
               InputStream instreams = resEntity.getContent(); 
               String uploadSysUrl = "D://erweima/";
               File saveFile = new File(uploadSysUrl+id+".png");

               // 判断这个文件（saveFile）是否存在
               if (!saveFile.getParentFile().exists()) {
                   // 如果不存在就创建这个文件夹
                   saveFile.getParentFile().mkdirs();
               }

               saveToImgByInputStream(instreams, uploadSysUrl, id+".png");
            }
        }

        httpPost.abort();
        return result;

    } 

 	/* @param instreams 二进制流
    * @param imgPath 图片的保存路径
    * @param imgName 图片的名称
    * @return
    *      1：保存正常
    *      0：保存失败
    */
   public static int saveToImgByInputStream(InputStream instreams,String imgPath,String imgName){

       int stateInt = 1;
       if(instreams != null){
           try {

               File file=new File(imgPath+imgName);//可以是任何图片格式.jpg,.png等
               FileOutputStream fos=new FileOutputStream(file); 

               byte[] b = new byte[1024];
               int nRead = 0;
               while ((nRead = instreams.read(b)) != -1) {
                   fos.write(b, 0, nRead);
               }
               
               fos.flush();
               fos.close();          
           } catch (Exception e) {
               stateInt = 0;
               e.printStackTrace();
           } finally {
               try {
                instreams.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
           }
       }

       return stateInt;

   }

//然后是图片重合和增加字体
//
// 
//
//public static void changeImage(String imageurl,String i){
//
//        try { 
//
////            InputStream imagein = new FileInputStream(
//
////                    "D:/systemAvatarNew1.png");
//
////            InputStream imagein2 = new FileInputStream(
//
////                    "D:/qqfile/1852230493/FileRecv/4-02.png");
//
//            InputStream imagein = new FileInputStream(
//
//                    "D:/1.png");
//
//            InputStream imagein2 = new FileInputStream(
//
//                    imageurl);
//
// 
//
//            BufferedImage image = ImageIO.read(imagein);
//
//            BufferedImage image2 = ImageIO.read(imagein2); 
//
//            //image2.getWidth() - 160, image2.getHeight() - 155,
//
//            Graphics g = image.getGraphics();
//
////            g.drawImage(image2, 300, 230, 410,422,null);
//
//            g.drawImage(image2, image.getWidth() - image2.getWidth(),
//
//                    image.getHeight() - image2.getHeight(),
//
//                    340,349,null);
//
//            OutputStream outImage = new FileOutputStream(imageurl);
//            JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(outImage);
//
//            enc.encode(image);
//
// 
//
// 
//
//            BufferedImage bimg=ImageIO.read(new FileInputStream(imageurl));  
//
//            //得到Graphics2D 对象  
//
//            Graphics2D g2d=(Graphics2D)bimg.getGraphics();  
//
//            //设置颜色和画笔粗细  
//
////            g2d.setColor(Color.black);  
//
//            g2d.setStroke(new BasicStroke(5));  
//
//            //String pathString = "D://qqfile/1852230493/FileRecv/SourceHanSansCN-/SourceHanSansCN-Heavy.otf";
//
////            Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, new File(pathString));
//
// 
//
//            g2d.setFont(new Font("微软雅黑", Font.PLAIN, 36));  
//
//            //g2d.setFont(Loadfont.loadFont(pathString, 45));  
//
//            //绘制图案或文字  
//
//            g2d.drawString("编号: "+i, 320, 700);  
//
//          //  g2d.drawString(i, 450, 700);    
//
// 
//
//            ImageIO.write(bimg, "JPG",new FileOutputStream(imageurl));
//
// 
//
// 
//
////            File fromFile = new File(imageurl);  
////
////            File toFile = new File(imageurl);  
////
////            Image1 Image1 =new Image1();
////
////            Image1.resizePng(fromFile, toFile, 1000, 1000, false);
//
// 
//
// 
//
// 
//
//            imagein.close();
//
//            imagein2.close();
//
//            outImage.close();
//
//        } catch (Exception e) {
//
//            e.printStackTrace();
//
//        }
//
//    }

   
   //
// public static CloseableHttpClient createSSLClientDefault() {
//     try {
//         SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
//             //信任所有
//             public boolean isTrusted(X509Certificate[] chain,
//                                      String authType) throws CertificateException {
//                 return true;
//             }
//         }).build();
//         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
//         return HttpClients.custom().setSSLSocketFactory(sslsf).build();
//     } catch (KeyManagementException e) {
////         log.error("", e);
//     } catch (NoSuchAlgorithmException e) {
////         log.error("", e);
//     } catch (KeyStoreException e) {
////         log.error("", e);
//     }
//     return HttpClients.createDefault();
// }
}
